package com.lkd.job;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lkd.common.VMSystem;
import com.lkd.entity.VendingMachineEntity;
import com.lkd.feign.VMService;
import com.lkd.service.VendingMachineService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import com.xxl.job.core.util.ShardingUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class AutoChannelJob {
    @Autowired
    private VendingMachineService vendingMachineService;
    @XxlJob("autoChannel")
    public ReturnT<String> autoChannel(String param) throws Exception{
        ShardingUtil.ShardingVO shardingVo = ShardingUtil.getShardingVo();
        int total = shardingVo.getTotal();
        int index = shardingVo.getIndex();
        log.info("分片总数="+total+"当前分片索引="+index);
        XxlJobLogger.log("分片总数="+total+"当前分片索引="+index);
        //根据状态查询售货机列表
        LambdaQueryWrapper<VendingMachineEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(VendingMachineEntity::getVmStatus, VMSystem.VM_STATUS_RUNNING)
                .apply("mod(id,"+total+")= "+index);
        List<VendingMachineEntity> lists = vendingMachineService.list(queryWrapper);
        //遍历售货机列表，发送消息
        lists.forEach(c->{
            XxlJobLogger.log("调用发送EMQ");
            vendingMachineService.sendSupply(c.getInnerCode());
        });
        return ReturnT.SUCCESS;
    }
}
